package net.flyinggroup.reactor.handson.fn;

import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;

import java.nio.charset.StandardCharsets;
import java.util.Optional;


public class ReactiveFunction {
    private final HandlerFunction<ServerResponse> helloHandler = request -> {
        Optional<String> name = request.queryParam("name");
        return ServerResponse.ok().body(BodyInserters.fromValue("Hello to " + name.orElse("theworld")));
    };

    private final RouterFunction<ServerResponse> helloRoute = RouterFunctions.route(RequestPredicates.path("/hello"), helloHandler);

    public RouterFunction<ServerResponse> getFunction() {
        return helloRoute.filter((request, next) -> {
            if (request.headers().acceptCharset().contains(StandardCharsets.UTF_8)) {
                return next.handle(request);
            } else {
                return ServerResponse.status(HttpStatus.BAD_REQUEST).build();
            }
        });
    }
}
